package sg.java.concepts.conditions;

/**
 * This class illustrates the accidental assignment principle.
 * 
 * @author Oh Chin Boon | java.sg | chinboon.oh2@gmail.com
 * @version 1
 * @since August 09, 2011.
 * @see <a href="http://java.sg/preventing-accidental-assignment">Accidental
 *      Assignment Principle</a>
 * 
 */
public class AccidentalAssignmentPrincipleApp {
	public static void main(String args[]) {
		final boolean MARRIED = true;
		boolean maritialStatus;

		// set maritialStatus to true
		maritialStatus = true;

		// lets check if Tom is engaged
		if (maritialStatus == MARRIED) {
			System.out
					.println("Ok it is true that Tom is engaged, lets move on..");
		}

		// ok lets ask Tom in a twisted way, instead of asking directly if
		// he was married, lets ask if Tom was not married!
		if (maritialStatus = !MARRIED) {
			// unfortunately, that didn't happen, the above condition didn't
			// check if Tom was not married either, it accidentally assigned
			// !MARRIED (false) to the boolean variable maritialStatus.
			System.out.println("Yay! Tom is not married");
		}

		// a second lady came by Tom and ask if Tom was married, all over again
		if (maritialStatus != MARRIED) {
			// due to the mistake of the above accidental assignment, Tom was
			// "unmarried".
			System.out.println("Hey Judy! Tom is single!11!");
		}

		// lets "reset" Tom, hey.
		maritialStatus = true;

		// a safer way of comparison, avoiding accidental assignment
		if (MARRIED == maritialStatus) {
			System.out.println("I can safely assume Tom is married. :/");
		}

		// this will not compile as it is compile-time checked
		// "The final local variable MARRIED cannot be assigned. It must be
		// blank and not using a compound assignment"
		// un-comment this to try, you will hit a compile-time error.
		// if (MARRIED = maritialStatus) {
		// }
	}
}
